package wh.coach.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.extern.slf4j.Slf4j;

/**
 * @author hangwen
 * @date 2023/12/13
 */
@Slf4j
public class JsonUtils {

    private static final ObjectMapper DEFAULT_MAPPER = new ObjectMapper();

    public static <T> T toJavaObject(final String json, final Class<T> type) {
        return toJavaObject(json, type, DEFAULT_MAPPER);
    }

    public static <T> T toJavaObject(final String json, final Class<T> type, final ObjectMapper objectMapper) {
        try {
            return objectMapper.readValue(json, type);
        } catch (JsonProcessingException e) {
            log.error("occurs error while read json [{}] to object [{}],cause by [{}]", json, type.getName(), e.getMessage());

            throw new RuntimeException(e);
        }
    }

    public static String toJsonString(final Object object) {
        return toJsonString(object, DEFAULT_MAPPER);
    }

    public static String toJsonString(final Object object, final ObjectMapper objectMapper) {
        try {
            return objectMapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            log.error("occurs error while write json from object [{}],cause by [{}]", object, e.getMessage());

            throw new RuntimeException(e);
        }
    }
}
